package com.base.components.database.dao.base;

import com.base.components.common.util.ConvertUtil;
import org.hibernate.HibernateException;
import org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl;
import org.hibernate.property.access.internal.PropertyAccessStrategyChainedImpl;
import org.hibernate.property.access.internal.PropertyAccessStrategyFieldImpl;
import org.hibernate.property.access.internal.PropertyAccessStrategyMapImpl;
import org.hibernate.property.access.spi.Setter;
import org.hibernate.transform.AliasedTupleSubsetResultTransformer;

import java.util.Arrays;

/**
 * ConvertTypeAliasToBeanResultTransformer
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version v1.0.0
 * @date 2019-02-15 9:22
 */
public class ConvertTypeAliasToBeanResultTransformer extends AliasedTupleSubsetResultTransformer {
  private static final long serialVersionUID = 6393244924109838321L;
  private final Class resultClass;
  private boolean isInitialized;
  private String[] aliases;
  private Setter[] setters;
  private Class<?>[] setterTypes;

  /** 不推荐，性能不好 */
  @Deprecated
  public ConvertTypeAliasToBeanResultTransformer(Class resultClass) {
    if ( resultClass == null ) {
      throw new IllegalArgumentException( "resultClass cannot be null" );
    }
    isInitialized = false;
    this.resultClass = resultClass;
  }

  @Override
  public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
  }

  @Override
  public Object transformTuple(Object[] tuple, String[] aliases) {
    Object result;

    try {
      if ( ! isInitialized ) {
        initialize( aliases );
      }
      else {
        check( aliases );
      }

      result = resultClass.newInstance();

      for ( int i = 0; i < aliases.length; i++ ) {
        if ( setters[i] != null ) {
          Object val = tuple[i];
          Class<?> setterType = setterTypes[i];
          if(setterType != null && val != null && !setterType.isAssignableFrom(val.getClass())){
            setters[i].set( result, ConvertUtil.convert(val, setterType), null );
          }
          else{
            setters[i].set( result, val, null );
          }
        }
      }
    }
    catch ( Exception e ) {
      throw new HibernateException("Could not instantiate resultClass: " + resultClass.getName(), e);
    }
    return result;
  }

  private void initialize(String[] aliases) {
    PropertyAccessStrategyChainedImpl propertyAccessStrategy = new PropertyAccessStrategyChainedImpl(
      PropertyAccessStrategyBasicImpl.INSTANCE,
      PropertyAccessStrategyFieldImpl.INSTANCE,
      PropertyAccessStrategyMapImpl.INSTANCE
    );
    this.aliases = new String[ aliases.length ];
    setters = new Setter[ aliases.length ];
    setterTypes = new Class[ aliases.length ];
    for ( int i = 0; i < aliases.length; i++ ) {
      String alias = aliases[ i ];
      if ( alias != null ) {
        this.aliases[ i ] = alias;
        Setter setter = propertyAccessStrategy.buildPropertyAccess(resultClass, alias).getSetter();
        setters[ i ] = setter;
        setterTypes[i] = setter.getMethod().getParameterTypes()[0];
      }
    }
    isInitialized = true;
  }

  private void check(String[] aliases) {
    if ( ! Arrays.equals(aliases, this.aliases ) ) {
      throw new IllegalStateException(
        "aliases are different from what is cached; aliases=" + Arrays.asList( aliases ) +
          " cached=" + Arrays.asList( this.aliases ) );
    }
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ConvertTypeAliasToBeanResultTransformer that = (ConvertTypeAliasToBeanResultTransformer) o;

    return resultClass.equals(that.resultClass) && Arrays.equals(aliases, that.aliases);
  }

  @Override
  public int hashCode() {
    int result = resultClass.hashCode();
    result = 31 * result + ( aliases != null ? Arrays.hashCode( aliases ) : 0 );
    return result;
  }

}
